﻿using Microsoft.Win32;
using RFIDLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace txtTEST
{
    public partial class a_itc : Form
    {

        MES_Platform.MES_Platform mes = new MES_Platform.MES_Platform();



        [DllImport("sa_demo_A.dll", EntryPoint = "ZLGKey", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int ZLGKey(
                          byte[] iSeedArray,          // seed数组
                          short iSeedArraySize,       // seed数组大小
                          char[] iSecurityLevel,        // 安全级别 1,3,5...
                          char[] iVariant,            // 其他数据, 可设置为空
                          byte[] iKeyArray,           // key数组, 空间由用户构造
                          short[] iKeyArraySize       // key数组大小, 函数返回时为key数组实际大小
                          );


        RFID_Class rFID_Class = new RFID_Class();

        public  a_itc()
        {
            InitializeComponent();

            //string Station = "P10";
            //var parrern = @"^(O|P)(10|[1-9])$";
            //var OK = Regex.IsMatch(Station, parrern);
            ;


            //short[] key_size = new short[2];


            //byte[] keyArray = new byte[4];
            //byte[] keyArray1 = new byte[4];
            //byte[] keyArray2 = HexStrToBytes("C7 FF 53 7C");

            //ZLGKey(keyArray2, (short)keyArray2.Length, new char[1], new char[1], keyArray, key_size);
            //AsLev1(keyArray2, keyArray1);
            ;

            //bool[] All_value = new bool[2] { true,false};
            //bool[] EVAL = new bool[2];

            //while (true)
            //{

            //    for (int i = 0; i < All_value.Length; i++)
            //    {
            //        if (All_value[i] == EVAL[i])
            //        {
            //            continue;
            //        }
            //        EVAL[i] = All_value[i];
            //        if (All_value[i])
            //        {
            //            ;
            //        }
            //    }
            //}
            //;

            string mes = "";
            string RFID_Class = string.Empty;


            //rFID_Class.Check3("P1","D", "D01A2405080001P1P2P3P4P");
            //string[] RFID_value = new string[2] { "D01A2405080001NG\r\n", "D01B2405080001P1P2" };
            //string[] RFID_value2 = new string[2] { "",""};
            //bool[] RFID_state = new bool[2];
            //RFID_value2[0] = RFID_value[0].Replace("\r", "").Replace("\n", "");

            //int Rut =  rFID_Class.RFID_init("COM4", 115200, out mes);
            //if (Rut!=0)
            //{
            //    ;
            //    //var uuuuu = rFID_Class.RFID_Check("P5","D",out RFID_state,out RFID_value, out mes);

            //    //var hhhhhh = rFID_Class.RFIDState_Write("P5", new string[2] { "OK", "OK"}, out RFID_value, out mes);
            //    //var hhhhhh2 = rFID_Class.RFIDState_Write("P3", new string[2] { "NG", "OK" }, RFID_value,out RFID_value, out mes);

            //   // MessageBox.Show(mes);
            //    ;
            //}

            //rFID_Class.RFID_Dispose(out mes);

            ;
            //string RFID = "D012405080001P1P2P3P4P5";

            //string Math_str = RFID.Substring(13);
            ////判断机型
            //var mode = RFID.Substring(0,2).Contains("D0");
            ////判断是否有NG出现
            //var mode2 = RFID.Contains("NG");
            ////判断规则
            //var parrern = @"([OPR]1)+([OPR]2)+([OPR]3)+([OPR]4)+([OPR]5)$";
            //var OK = Regex.IsMatch(Math_str, parrern);



            //int[] buf = new int[2] { 3144, 3233 };
            //char[] str = Array.ConvertAll(buf, c => Convert.ToChar(c));
            //string Rfid_str = new string(str);
            //;

            //byte[] messageBytes = Encoding.ASCII.GetBytes(RFID);
            //char[] messageBytes2 = RFID.ToArray();
            //int registerCount = (int)Math.Ceiling((double)messageBytes.Length / 2);
            //int[] registers = new int[registerCount];
            //for (int i = 0; i < registerCount; i++)
            //{
            //    int hi = i * 2 < messageBytes.Length ? messageBytes[i * 2] : 0;
            //    int lo = i * 2 + 1 < messageBytes.Length ? messageBytes[i * 2 + 1] : 0;
            //    registers[i] = (hi << 8) | lo;
            //}
            //;
        }

        private void a_itc_Load(object sender, EventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            //if (button1.Text =="OFF")
            //{
            //    timer1.Enabled = true;
            //    button1.Text = "ON";
            //}
            //else if (button1.Text == "OFF")
            //{
            //    timer1.Enabled = false;
            //    button1.Text = "OFF";
            //}
        }


        bool FlagStart = false;
       bool[] State = new bool[] { true, true };
        string[] Write_Snstate = new string[] { "OK", "OK" };
        string[] Value_Sn = new string[2];
        string Msg = "";
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                while (true)
                {

                    if (!FlagStart)
                    {
                      var hhh =  rFID_Class.RFID_Check("P7", "D", out State, out Value_Sn, out Msg);
                        if (hhh!=0)
                        {
                            MessageBox.Show("错误");
                        }
                      var kkk =  rFID_Class.RFIDState_Write("P7", Write_Snstate, out Value_Sn, out Msg);
                        if (hhh != 0)
                        {
                            MessageBox.Show("错误");
                        }
                    }
                }
            }
            catch (Exception)
            {
                ;
            }

        }





        private int GetStationLength(string Station)
        {
            try
            {
                switch (Station)
                {
                    case "P1": return 16;
                    case "P2": return 18;
                    case "P3": return 20;
                    case "P4": return 22;
                    case "P5": return 24;
                    case "P6": return 26;
                    case "P7": return 28;
                    case "P8": return 30;
                    case "P9": return 32;
                    case "P10": return 34;
                    default: return 0;
                }
            }
            catch (Exception)
            {
                return 0;
            }

        }

        public static void AsLev1(byte[] iSeedArray, byte[] ioKeyArray)
        {
            // 确保输入数组的长度为4
            if (iSeedArray.Length != 4 || ioKeyArray.Length != 4)
            {
                throw new ArgumentException("输入数组和输出数组长度必须为4");
            }

            uint constant = 0x20575043;
            uint seed = 0;

            // 构建种子值
            seed = iSeedArray[0];
            seed <<= 8;
            seed += iSeedArray[1];
            seed <<= 8;
            seed += iSeedArray[2];
            seed <<= 8;
            seed += iSeedArray[3];

            // 进行35次迭代
            for (int i = 0; i < 35; i++)
            {
                if ((seed & 0x80000000) != 0)
                {
                    seed = (seed << 1) ^ constant;
                }
                else
                {
                    seed = seed << 1;
                }
            }
            byte[] buf = new byte[4];
            // 填充输出数组
            for (int j = 0; j < 4; j++)
            {
                ioKeyArray[j] = (byte)((seed >> (j * 8)) & 0xFF);
            }

            Array.Reverse(ioKeyArray);
        }

        public byte[] HexStrToBytes(string str)
        {
            str = str.Replace(" ", "");
            if ((str.Length % 2) != 0)
                str += " ";
            byte[] bts = new byte[str.Length / 2];
            for (int i = 0; i < bts.Length; i++)
                bts[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
            return bts;
        }


        private void pictureBox1_DragEnter(object sender, DragEventArgs e)
        {
            if ((e.Data.GetDataPresent(typeof(Button))))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void pictureBox1_DragDrop(object sender, DragEventArgs e)
        {
            if ((e.Data.GetDataPresent(typeof(Button))))
            {
                Button btnInstance = new Button();
                FieldInfo info, info2, info3;
                object obj, obj2, obj3;
                info = e.Data.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance);
                obj = info.GetValue(e.Data);
                info2 = obj.GetType().GetField("data", BindingFlags.NonPublic | BindingFlags.Instance);
                obj2 = info2.GetValue(obj);
                System.Collections.Hashtable dataItems = (obj2 as System.Collections.Hashtable);
                foreach (var dataItem in dataItems)
                {
                    System.Collections.DictionaryEntry dictEntry = (System.Collections.DictionaryEntry)dataItem;
                    object key = dictEntry.Key;
                    object value = dictEntry.Value;
                    info3 = value.GetType().GetField("data", BindingFlags.Public | BindingFlags.Instance);
                    obj3 = info3.GetValue(value);
                    btnInstance = obj3 as Button; // 此处转化成功，成功获取到传递进来的button实例。
                }
                try
                {
                    Button bt = new Button();
                    bt.ImageAlign = ContentAlignment.MiddleLeft;
                    bt.TextAlign = ContentAlignment.MiddleRight;
                    bt.ImageList = imageList1;
                    bt.ImageIndex = int.Parse(btnInstance.Tag.ToString());
                    bt.AutoSize = false;
                    bt.Location = this.PointToClient(new Point(e.X - 124, e.Y - 48 / 2));
                    bt.Size = new Size(136, 48);
                    bt.ForeColor = Color.Black;
                    bt.Text = btnInstance.Text;
                    bt.Name = btnInstance.Name;
                    bt.BackColor = Color.Transparent;
                    // 在控件增加到窗体里时做一个判断，如果是开始 和结束只能存在一个
                    foreach (Control control in this.pictureBox1.Controls)
                    {
                        if (control.Name == btnInstance.Name || control.Name == btnInstance.Name)
                        {
                            MessageBox.Show("已存在，不能添加");
                            return;
                        }
                    }
                    pictureBox1.Controls.Add(bt);
                    //拖拽移动
                    MoveBlock(bt);
                    bt.ContextMenuStrip = this.contextMenuStrip1;
                    bt.Click += new System.EventHandler(bt_click);
                    huoqu_kongjian();
                    bt.BringToFront();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            Image ImgDeal(Image img, byte alpha, int width, int height)
            {
                var bmpSize = new Bitmap(width, height);
                using (var g = Graphics.FromImage(bmpSize))
                {
                    g.DrawImage(img, new Rectangle(0, 0, width, height));
                }
                var bmpAlpha = new Bitmap(width, height);
                for (int i = 0; i < width; i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        var color = bmpSize.GetPixel(i, j);
                        bmpAlpha.SetPixel(i, j, Color.FromArgb(alpha, color));
                    }
                }
                return (Image)bmpAlpha.Clone();
            }

            // 定义按钮拖动 轨迹的样式
            private void bt_GiveFeedback(object sender, GiveFeedbackEventArgs e)
            {
                e.UseDefaultCursors = false;
                if (e.Effect == DragDropEffects.None)
                {
                    //var img = ImgDeal(imageList1.Images[1], 70, 136,48);
                    //Cursor.Current = new Cursor(((Bitmap)img).GetHicon());
                }
                else
                {
                    var img = ImgDeal(imageList1.Images[1], 70, 136, 48);
                    Cursor.Current = new Cursor(((Bitmap)img).GetHicon());
                }
            }


        }
    }

}
